package com.xmmj.baselibrary.utils.viewadapter.viewpager

import androidx.databinding.BindingAdapter
import androidx.fragment.app.FragmentActivity
import android.content.ContextWrapper
import androidx.fragment.app.Fragment
import androidx.viewpager.widget.ViewPager
import com.xmmj.baselibrary.utils.adapter.viewpager.ViewPagerAdapter

@BindingAdapter(value = ["fragments"], requireAll = false)
fun setFragments(
    viewPager: ViewPager,
    fragments: List<Fragment>
) {
    if (viewPager.context is FragmentActivity) {
        viewPager.adapter = ViewPagerAdapter(
            (viewPager.context as FragmentActivity).supportFragmentManager,
            fragments
        )
        viewPager.offscreenPageLimit = fragments.size
    } else if (viewPager.context is ContextWrapper) {
        viewPager.adapter = ViewPagerAdapter(
            ((viewPager.context as ContextWrapper).baseContext as FragmentActivity).supportFragmentManager,
            fragments
        )
        viewPager.offscreenPageLimit = fragments.size
    }
}

@BindingAdapter(value = ["onPageChangeListener"], requireAll = false)
fun addOnPageChangeListener(
    viewPager: ViewPager,
    onPageChangeListener: ViewPager.OnPageChangeListener
) {
    onPageChangeListener.let {
        viewPager.addOnPageChangeListener(it)
    }
}

@BindingAdapter(value = ["position"], requireAll = false)
fun setPosition(viewPager: ViewPager, position: Int) {
    viewPager.setCurrentItem(position, false)
}
